package com.cskaoyan.mall.controller.admin;

import com.cskaoyan.mall.model.sql.Result;
import com.cskaoyan.mall.model.sql.User;
import com.cskaoyan.mall.service.UserService;
import com.cskaoyan.mall.service.implement.UserServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/api/admin/user/*")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    Gson gson = new Gson();

    /***********************************************    doPost   *******************************************************/
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/user/", "");
        if("".equals(action)){*/

    }
    /***********************************************    doGet   *******************************************************/
    protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String requestURI = request.getRequestURI();
            String action = requestURI.replace("/api/admin/user/", "");
            if("allUser".equals(action)){
                allUser(request,response);
            }else if ("deleteUser".equals(action)){
                deleteUser(request,response);
            }else if ("searchUser".equals(action)){
                searchUser(request,response);
            }

    }

    /**
     * 模糊查询User
     * @param request
     * @param response
     */
    private void searchUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String word = (String) request.getParameter("word");
        List<User> userList=userService.searchUser(word);
        response.getWriter().println(gson.toJson(Result.ok(userList)));
    }

    /**
     * 删除User   参数ID
     * @param request
     * @param response
     */
    private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        userService.deleteUser(id);
        response.getWriter().println(gson.toJson(Result.ok()));
    }


    private void allUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<User> users = userService.allUser(request, response);
        response.getWriter().println(gson.toJson(Result.ok(users)));
    }
}